<template>
    <div class="trigger-configuration-new-content-box" v-show="isShowMasterData">
        <div class="trigger-configuration-new-content-item">
            <div class="trigger-configuration-new-content-item-title">
                <div class="name">{{ field.cnName }}</div>
                <i v-if="field.required">*</i>
            </div>
            <div class="trigger-configuration-new-content-item-select">
                <el-dropdown @command="value => handleCommand(value)" trigger="click">
                    <span class="el-dropdown-link">
                        {{ getValueTypeText(valueType) }} <i class="iconfont icon-caret-down"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item v-for="item in field.valueTypeList" :key="item.enName" :command="item.enName">
                            {{ item.cnName }}
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
            <div class="trigger-configuration-new-content-item-value">
                <fixedInput
                    v-if="valueType == '1'"
                    :value="currentValue"
                    :field="findData(toFieldList, field.enName)"
                    @input="handleFixedInput"
                ></fixedInput>
                <el-cascader
                    v-else-if="valueType == '2'"
                    :value="currentValue"
                    :options="filterAndDisableData(fromFieldList, field)"
                    :props="cascaderProps"
                    :disabled="jsonObjectField"
                    popper-class="trigger-configuration-new_cascader-popover conditional-config_cascader-popover"
                    placement="bottom-end"
                    placeholder="请选择"
                    @change="handleCorrespondenceChange"
                    @click.native="changeEmpty"
                    filterable
                    clearable
                    ref="cascaderHandle"
                >
                  <template slot-scope="{ data }">
                    <div class="item" :class="data.cnName.length > 12 ? 'item-overflow' : ''" :title="data.cnName">{{ data.cnName }}</div>
                </template>
                </el-cascader>
                <ConnectorModuleRuleFormItemApp
                    v-else-if="valueType == '3'"
                    :currentToField="findData(toFieldList, field.enName)"
                    :isDisabledFromFieldSelect="false"
                    :fromFieldList="fromFieldList"
                    :fromBizTypeName="findData(toFieldList, field.enName).cnName"
                    :value="currentValue"
                    :fromPageType="fromPageType"
                    clearable
                    @change="handleApiChange"
                >
                </ConnectorModuleRuleFormItemApp>

            </div>
        </div>
        <template v-if="field.children && field.children.length">
            <div class="trigger-configuration-new-content-box__children">
            <TriggerConfigurationItem  
                v-for="(subField, index) in field.children"
                :key="subField.enName"
				:field="subField"
				:index="index"
				:fromFieldList="getSubFromFields(subField, value)"
				:toFieldList="field.children"
				:isShowMasterData="true"
                :valueType="getSubFieldValueOrType(subField, 'valueType')"
                :value="getSubFieldValueOrType(subField, 'value')"
                :parentField="field"
                @change="handleItemChange($event, index)"
            ></TriggerConfigurationItem>
            </div>
        </template>
    </div>
</template>
  
<script>
import { matchFieldToTransform } from '@src/modules/connector/util'
import fixedInput from '@src/modules/trigger/view/setting/components/trigger_condition/components/fiexdInput.vue';
import ConnectorModuleRuleFormItemApp from '@src/modules/connector/components/rule-form/item-form-app'
import state from '@src/modules/trigger/view/setting/util/state.js';
import actionMixin from '../mixins/actionMixin';

export default {
    name: 'TriggerConfigurationItem',
    mixins: [actionMixin],
    props: {
        // 主数据的字段
        field: {
            type: Object,
            required: true,
            default: () => ({})
        },
        // 判断符
        valueType: {
            type: String,
            required: true,
            default: '',
        },
        // 值
        value: {
            type: Array,
            required: true,
            default: () => []
        },
        fromFieldList : {
            type: Array,
            required: true,
            default: () => []
        },
        toFieldList: {
            type: Array,
            required: true,
            default: () => []
        },
        // 是否显示
        isShowMasterData: {
            type: Boolean,
            required: true,
            default: () => false
        },
        parentField: {
            type: Object,
            default: () => ({})
        },
        optionValue: {
            type: Object,
            default: () => ({})
        }
    },
    components: {
        fixedInput,
        ConnectorModuleRuleFormItemApp
    },
    computed: {
        state() {
            return state;
        },
        cascaderProps() {
            return {
                checkStrictly: true,
                label: 'cnName',
                value: 'enName',
                emitPath: false,
                expandTrigger: 'hover',
            };
        },
        jsonTypeField() {
            return ['jsonArray', 'jsonObject']
        },
        jsonField() {
            return this.jsonTypeField.includes(this.field.fieldType)
        },
        jsonObjectField() {
            return this.field.fieldType.includes('jsonObject')
        },
        jsonValue() {
            if(this.value?.[0]) {
                try {
                   return JSON.parse(this.value[0])
                } catch(e) {}
            }
            return {}
        },
        currentValue() {
            // 如果数据未固定至其未多级多选，则需要转换给element能用的数据
            if (this.valueType == '1' && this.field.fieldType == 'cascader' && this.field.setting && this.field.setting.isMulti) {
                return this.value.map(item => {
                    return JSON.parse(item).map(i => {
                        if (Array.isArray(i)) { 
                            return i
                        }
                        return i.split('/')
                    })
                })
            }
            if(this.jsonField) {
                return this.jsonValue?.fromEnName || ''
            } 
            if(this.valueType == '1') {
                return this.value
            }
            return this.value[0]
        },
        fromPageType() {
            return 'newTrigger'
        }
    },
    methods: {
        getSubFieldValueOrType(field, key) {
            const jsonSubFieldValue = this.jsonValue?.relationShip || {}
            const subFieldValue = jsonSubFieldValue[field.enName]?.[key]
            if(subFieldValue) {
                return key === 'valueType' ? subFieldValue : [subFieldValue]
            }
            return key === 'valueType' ? this.valueType : []
        },
        handleItemChange(value, index) {
            const field = this.field.children[index]
            const jsonSubFieldValue = this.jsonValue?.relationShip || {}
            jsonSubFieldValue[field.enName] = {
                ...value,
                value: value.value?.[0] || ''
            }

            const newValueObject = {
                ...this.jsonValue,
                relationShip: jsonSubFieldValue
            }

            if(this.jsonObjectField && !Reflect.has(newValueObject, 'triggerSubform')) {
                newValueObject.triggerSubform = 1
                newValueObject.fromEnName = ''
            }
            this.optionValue.value = [JSON.stringify(newValueObject)]
        },
        getSubFromFields(field, parentValue) {
            if(this.field.fieldType.includes('jsonArray')) {
                if(!this.currentValue) return []
                if(parentValue && Array.isArray(parentValue)) {
                    const fromFieldList = this.fromFieldList.filter(field=> field.fieldType !== 'jsonArray' || field.enName === this.currentValue)
                    return fromFieldList
                }
            }
            if(this.field.fieldType.includes('jsonObject')) {
                return this.fromFieldList.filter(field=> field.fieldType !== 'jsonArray')
            }
            return []
        },
        // 判断符修改
        handleCommand(value) {
            this.$emit('change', {
                valueType: value,
                value: [],
            });
        },
        // 根据判断符找到对应的判断符中文名
        getValueTypeText(index) {
            const field = this.toFieldList.find(field=> field.enName === this.field.enName)
            if(!field) return ''
            return field.valueTypeList.find(item => item.enName == this.valueType)?.cnName;
        },
        // 固定值修改
        handleFixedInput(value, _comFieldInfo) {
            this.$emit('change', {
                valueType: this.valueType,
                value: value,
                _compatibilityField: _comFieldInfo
            });
        },
        // 对应字段修改
        handleCorrespondenceChange(value) {
            // 关闭联级选择器
            this.$refs.cascaderHandle.dropDownVisible = false;

            if(this.jsonField)  {
                const jsonArrayValue = {
                    triggerSubform: 1,
                    fromEnName: value,
                    relationShip: {}
                }
                return this.$emit('change', {
                    valueType: this.valueType,
                    value: [JSON.stringify(jsonArrayValue)],
                });
            }

            this.$emit('change', {
                valueType: this.valueType,
                value: [value],
            });
        },
        // 字段来自api修改
        handleApiChange(value) {
            this.$emit('change', {
                valueType: this.valueType,
                value: Object.keys(value).length !== 0 ? [JSON.stringify(value)] : [],
                _compatibilityField: {
                    _isOtherFormExecute: true
                }
            });
        },
        // 在列表中根据flg找到对应元素
        findData(list, flg) {
            for (const item of list) {
                if (item.enName === flg) {
                    return item;
                }
                if (item.children) {
                    const result = this.findData(item.children, flg);
                    if (result.enName === flg) {
                        return result;
                    }
                }
            }
            return {};
        },
        // 对对应字段的数据进行过滤
        filterAndDisableData(data, field) {
            const enName = field.enName
            const targetField = this.findData(this.toFieldList, enName);

            function filterElement(element) {
                const item = {
                    ...element,
                    disabled: !matchFieldToTransform(targetField, element),
                };

                if (element.children) {
                    const filteredChildren = element.children.filter(child => filterElement(child)) || [];
                    if (filteredChildren.length > 0) {
                        item.children = filteredChildren;
                        return item;
                    } else {
                        delete item.children;
                    }
                }
                return matchFieldToTransform(targetField, item) || item.children ? item : null;
            }
            return data.map(element => filterElement(element)).filter(element => element !== null);
        },
        // 如果之前的节点有未选择的，需要修改文案进行引导
        changeEmpty() {
			state.parentNodeApiIdList.forEach(item => {
				// 判断有没有null
				if (item === null || item === undefined) {
					this.$nextTick(() => {
						document.querySelectorAll(".el-cascader-menu__empty-text").forEach((item) => {
							item.innerText = "请完成上级节点设置";
						});
					})
				}
			})
		},
    }
};
</script>

<style lang="scss">
@import '@src/modules/trigger/view/setting/style/cascader.scss';
</style>

<style scoped lang="scss">
::v-deep .el-dropdown-link {
	cursor: pointer;
}
.trigger-configuration-new-content-box {
    .trigger-configuration-new-content-item{
        display: flex;
        align-items: center;
        min-height: 32px;
        margin: 14px 0;
        &-title {
            // flex-shrink: 0;
            width: 160px;
            display: flex;
            align-items: center;
            margin-left: 22px;
            box-sizing: border-box;
            .name {
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
            }

            i {
                color: #f56c6c;
            }
        }

        &-select {
            flex-shrink: 0;
            min-width: 100px;
            display: flex;
            justify-content: end;
            align-items: center;
            margin-right: 8px;

            ::v-deep .el-dropdown {
                color: #8c8c8c;
            }
        }

        &-value {
            flex-shrink: 0;
            width: 100%;
            max-width: 224px;

            ::v-deep .el-cascader {
                width: 100%;
            }
        }
    }
    &__children {
        .trigger-configuration-new-content-item-title{
            padding-left: 10px;
        }
    }
}


</style>
